package com.domain.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.domain.common.AppLogger;
import com.domain.common.Result;
import com.domain.utils.NotNullUtils;
import com.domain.utils.UUIDUtils;
import com.domain.utils.alipay.AlipayConfig;
import com.domain.utils.alipay.BindAlipay;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


@Controller
@RequestMapping("/alipay")
public class AliPayController {

    /**
     * 日志
     */
    private static Logger logger = AppLogger.getLogger(AliPayController.class.getSimpleName(), Level.INFO.toString(), true);

    /**
     * 跳转到授权界面
     */
    @RequestMapping(value = "/openauth", method = RequestMethod.POST)
    @ResponseBody
    public String openauth(HttpServletRequest request, HttpServletResponse response) {

        try {
            Map<String, String> maps = new HashMap<String, String>();
            //页面回调地址 必须与应用中的设置一样（待设置）
            String redirect_uri = "http://47.99.188.244/alipay/getUserInfo";
            //回调地址必须经encode
            redirect_uri = URLEncoder.encode(redirect_uri);
            //重定向到授权页面
            return "redirect:" + AlipayConfig.ALIPAY_URL + "?app_id=" + AlipayConfig.ALI_APPID + "&scope=auth_user&redirect_uri=" + redirect_uri;
        } catch (Exception e) {
            return "操作失败";
        }
    }

    /**
     * 获取用户信息
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
    @ResponseBody
    public String getUserInfo(HttpServletRequest request, HttpServletResponse response) {
        //获取支付宝GET过来反馈信息
        try {
            Map<String, String> params = new HashMap<String, String>();
            Map requestParams = request.getParameterMap();
            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == (values.length - 1)) ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }

            String accessToken = BindAlipay.buildRequest(params);
            String imf = "";
            if (NotNullUtils.isNotNullObject(accessToken)) {
                imf = BindAlipay.get(accessToken);
            }
            return imf;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 支付宝支付成功后.回调该接口
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/asynchronousNotification", method = RequestMethod.POST)
    @ResponseBody
    public boolean asynchronousNotification(HttpServletRequest request, HttpServletResponse response) {
        try {
            //获取支付宝POST过来反馈信息
            Map<String, String> params = new HashMap<>();
            Map requestParams = request.getParameterMap();
            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用。
                //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }
            //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
            //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
            boolean flag = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALI_ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.ALI_SIGN_TYPE);
            return flag;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return false;
        }
    }
}
